/**
 * 打包相对路径
 * js/css/img等静态资源_配置时间戳
 * 图片压缩
 * gzip压缩
 */
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}
const Timestamp = new Date().getTime()
const CompressionPlugin = require('compression-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  productionSourceMap: false,
  devServer: {
    port: 80,
    disableHostCheck: true // 微信公众号开调试配置
  },
  configureWebpack: {
    // css文件名_添加时间戳
    plugins: [
      new MiniCssExtractPlugin({
        filename: `static/css/[name].${Timestamp}.css`,
        chunkFilename: `static/css/[name].${Timestamp}.css`
      })
    ]
  },
  chainWebpack: (config) => {
    // 设置别名
		config.resolve.alias
      .set('@', resolve('src'))
    // js文件名_添加时间戳
    config.output
      .filename(`static/js/[name].${Timestamp}.js`)
      .chunkFilename(`static/js/[name].${Timestamp}.js`)
    // 图片压缩 && 添加时间戳
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({ bypassOnDebug: true })
      .end()
        .use('url-loader')
        .tap(options => {
          options.name = `static/img/[name].${Timestamp}.[ext]`
          options.fallback = {
            loader: 'file-loader',
            options: {
              name: `static/img/[name].${Timestamp}.[ext]`
            }
          }
          return options
        })

    // gzip压缩
    if (process.env.NODE_ENV !== 'development') {
      config.plugin('compressionPlugin')
        .use(new CompressionPlugin({
          test: /\.js$|\.html$|\.css/,
          threshold: 10240,
          deleteOriginalAssets: false // 不删除源文件
        }))
    }
	},
  parallel: true
}
